const { exec } = require('child_process')
const path = require('path')
const { app } = require('electron')

class InputMethodManager {
  constructor() {
    // 获取im-select.exe的绝对路径
    this.imSelectPath = path.join(
      app.isPackaged ? process.resourcesPath : app.getAppPath(),
      'resources',
      'tools',
      'im-select.exe'
    )
  }

  /**
   * 获取当前输入法标识符
   * @returns {Promise<string>} 输入法ID
   */
  getCurrentInputMethod() {
    return new Promise((resolve, reject) => {
      exec(`"${this.imSelectPath}"`, (error, stdout, stderr) => {
        if (error) {
          reject(new Error(`执行失败: ${error.message}`))
          return
        }
        if (stderr) {
          reject(new Error(`工具报错: ${stderr}`))
          return
        }
        resolve(stdout.trim())
      })
    })
  }

  /**
   * 切换到指定输入法
   * @param {string} imId 输入法标识符
   * @returns {Promise<boolean>} 是否切换成功
   */
  switchToInputMethod(imId) {
    return new Promise((resolve, reject) => {
      exec(`"${this.imSelectPath}" ${imId}`, (error, stdout, stderr) => {
        if (error) {
          reject(new Error(`切换失败: ${error.message}`))
          return
        }
        if (stderr) {
          reject(new Error(`工具报错: ${stderr}`))
          return
        }
        resolve(stdout.trim() === imId)
      })
    })
  }

  /**
   * 获取系统中所有输入法的ID和名称
   * @returns {Promise<Array<{id: string, name: string}>>} 输入法列表
   */
  getAllInputMethods() {
    return new Promise((resolve, reject) => {
      // 查询注册表中安装的输入法
      // 64位系统路径：HKLM\SYSTEM\CurrentControlSet\Control\Keyboard Layouts
      // 32位系统路径：HKLM\SYSTEM\CurrentControlSet\Control\Keyboard Layouts
      exec(
        'reg query "HKLM\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts" /s',
        (error, stdout, stderr) => {
          if (error) {
            reject(new Error(`查询注册表失败: ${error.message}`))
            return
          }
          if (stderr) {
            reject(new Error(`注册表查询错误: ${stderr}`))
            return
          }

          // 解析注册表输出，提取输入法ID和名称
          const imeList = []
          const lines = stdout.split('\r\n')
          let currentId = null

          lines.forEach((line) => {
            // 匹配输入法ID（8位十六进制数）
            const idMatch = line.match(/Keyboard Layouts\\([0-9A-Fa-f]{8})/)
            if (idMatch) {
              currentId = `0x${idMatch[1]}` // 转换为0x前缀的格式
            }

            // 匹配输入法名称
            const nameMatch = line.match(/Layout Text\s+REG_SZ\s+(.*)/)
            if (nameMatch && currentId) {
              imeList.push({
                id: currentId,
                name: nameMatch[1].trim()
              })
              currentId = null // 重置，避免重复匹配
            }
          })

          // 去重并返回
          const uniqueImeList = [...new Map(imeList.map((item) => [item.id, item])).values()]
          resolve(uniqueImeList)
        }
      )
    })
  }
}

// 导出单例实例
module.exports = new InputMethodManager()
